<template>
  <div>
    <div style="backgroud:#fff">
      <el-form-item label="角色名称">
        <el-input v-model="roleName" placeholder="请输入角色名称" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="small" @click="initData">
          搜索
        </el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </el-form-item>
      <div>
        <el-button type="success" size="small" @click="handleShowDialog">
          添加
        </el-button>
      </div>
    </div>

    <el-table :data="roles" stripe style="width: 100%">
      <el-table-column prop="roleName" label="角色名称" width="180" />
      <el-table-column prop="roleCode" label="角色code" width="180" />
      <el-table-column prop="createTime" label="创建时间" />

      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            size="small"
            type="warning"
            @click="handleShowAssignMenuDialog(scope.row)"
          >
            分配菜单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:50px">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="initData"
        @current-change="initData"
      />
    </div>

    <!-- 新增角色表单对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title">
        <el-form>
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="sysRole.roleName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色code" :label-width="formLabelWidth">
            <el-input v-model="sysRole.roleCode" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色介绍" :label-width="formLabelWidth">
            <el-input v-model="sysRole.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdateRole">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <!-- 分配菜单的对话框 -->
    <div>
      <el-dialog v-model="dialogAssignMenuVisible" title="分配菜单">
        <div>
          <el-tree
            :data="menus"
            ref="menuTree"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :default-checked-keys="checkedMenuIds"
            :props="defaultProps"
          />
        </div>

        <template #footer>
          <span class="dialog-footer" style="text-align:center">
            <el-button @click="dialogAssignMenuVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="handleAssignMenus2Role">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import {
  GetRoles,
  DeleteRoleById,
  SaveRole,
  GetRoleById,
  UpdateRole,
  AssignMenus2Role,
} from '@/api/sysRole'
import { GetNestedMenus, GetMenuIdsByRoleId } from '@/api/sysMenu'
import { ElMessage, ElMessageBox } from 'element-plus'

//5、给角色分配菜单
const dialogAssignMenuVisible = ref(false)
//5.1 弹出分配菜单的对话框
const handleShowAssignMenuDialog = async row => {
  //先清空缓存
  menus.value = []
  checkedMenuIds.value = []
  //查询菜单数据 在对话框中展示
  const { data } = await GetNestedMenus()
  //查询角色已分配的菜单id列表回显： 以后提交分配菜单给角色请求时还需要使用此处的角色id
  sysRole.value = row
  const result = await GetMenuIdsByRoleId(row.id)
  menus.value = data
  checkedMenuIds.value = result.data
  dialogAssignMenuVisible.value = true
}
//el-tree解析data数据的自定义属性配置：children指定要解析的子数据集合,label指定要解析的数据标题属性
const defaultProps = {
  children: 'children',
  label: 'title',
}
//默认设置选中的菜单id集合: 回显时不能查询父菜单id回显，只能查询子菜单(查询父id会导致它未选中的子菜单也会选中)
const checkedMenuIds = ref([])
//菜单列表
const menus = ref([])
//5.2 分配菜单
// menuTree用来绑定页面中定义了ref属性，并且值为menuTree的标签
const menuTree = ref()
//分配菜单对话框提交按钮事件函数
const handleAssignMenus2Role = async () => {
  //获取给那个角色分配菜单：roleId
  console.log('roleId:' + sysRole.value.id)
  //对话框中选中的菜单id列表：(全选、半选)
  // console.log('checkedMenuIds:' + checkedMenuIds.value)
  const checkedKeys = menuTree.value.getCheckedKeys()
  const halfCheckedKeys = menuTree.value.getHalfCheckedKeys()
  // console.log(checkedKeys, halfCheckedKeys)
  const menuIds = [...checkedKeys, ...halfCheckedKeys]
  await AssignMenus2Role(menuIds, sysRole.value.id)
  ElMessage.success('分配菜单成功')
  dialogAssignMenuVisible.value = false
}

const roleName = ref('')
//分页导航的属性和函数
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(30)
const roles = ref([])
//重置按钮事件函数
const reset = () => {
  pageNum.value = 1
  pageSize.value = 3
  roleName.value = ''
  initData()
}
//1、角色分页数据查询=======
onMounted(() => {
  //页面初始化时 查询第一页数据渲染展示
  initData()
})
//加载角色分页数据的函数
const initData = async () => {
  const { code, message, data } = await GetRoles(
    pageNum.value,
    pageSize.value,
    roleName.value
  )
  //code值的判断一会提取到 request.js中axios配置的响应拦截器中

  //data代表响应的分页对象
  total.value = data.total
  roles.value = data.list
}
//2、删除指定角色
const handleDelete = row => {
  console.log(row)
  ElMessageBox.confirm(`删除角色【${row.roleName}】，是否确认?`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    //确认
    .then(async () => {
      await DeleteRoleById(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //刷新页面数据
      initData()
    })
    //取消
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//3、新增角色
//新增对话框的属性和函数
const dialogFormVisible = ref(false)
const formLabelWidth = '120px'
const title = ref('新增角色')
const sysRole = ref({})
//打开新增对话框
const handleShowDialog = () => {
  title.value = '新增角色'
  sysRole.value = {}
  dialogFormVisible.value = true
}
//提交新增请求
const handleSaveRole = async () => {
  await SaveRole(sysRole.value)
  ElMessage.success('新增成功')
  //关闭对话框
  dialogFormVisible.value = false
  //刷新页面
  initData()
}
//4、更新角色
//查询回显：弹出对话框
const handleEdit = async row => {
  //查询要更新的角色回显
  // 回显复用新增的对话框，对话框中使用sysRole绑定数据展示
  const { data } = await GetRoleById(row.id)
  sysRole.value = data
  title.value = '更新角色'
  dialogFormVisible.value = true
}
//更新方法
const handleUpdateRole = async () => {
  await UpdateRole(sysRole.value)
  dialogFormVisible.value = false
  initData()
}
//提交按钮事件函数：新增和更新都会调用
const handleSaveOrUpdateRole = () => {
  if (sysRole.value.id) {
    //sysRole存在id表示更新
    handleUpdateRole()
  } else {
    //新增
    handleSaveRole()
  }
}
</script>
